import os
import sys
import shutil
from datetime import datetime

#测试连接正常
def connect_server(server_path):
    # 检查路径是否存在
    if os.path.exists(server_path):
        print(server_path,"连接成功！",datetime.now())

    else:
        print("连接不上，请检查")
        sys.exit(1)

#对于共享目录还有按照月份归类的，进入最新月份的目录，直接下载文件
def yuefen_dir_download(server_path, local_path, file_name_start,file_name_end):
    remotedir = [
        (os.path.join(server_path, filename), os.path.getmtime(os.path.join(server_path, filename)))
        for filename in os.listdir(server_path)
    ]
    remotedir.sort(key=lambda x: x[1], reverse=True)
    new_server_path = os.path.join(server_path, remotedir[0][0])
    download_file(new_server_path, local_path, file_name_start,file_name_end)


#对共享目录里是目标文件进行排序，取最新的文件复制
def download_file(server_path, local_path, file_name_start,file_name_end):
    try:
        # 列出共享目录里的文件列表
        remotedocfiles = [
            (os.path.join(server_path, filename), os.path.getmtime(os.path.join(server_path, filename)))
            for filename in os.listdir(server_path)
            if filename.startswith(file_name_start) and filename.endswith(file_name_end)
        ]

        # 测试目标文件为空
        if remotedocfiles == []:
            print('没有合适的文档')
            sys.exit(1)
        else:
            # 根据修改时间对文件进行排序
            remotedoc = sorted(remotedocfiles, key=lambda x: x[1], reverse=True)
            latest_remotefile = remotedoc[0][0]
            latest_remotefile_mtime = remotedoc[0][1]
            #找出本地文件的最新时间
            localdocfiles = [
                (os.path.join(local_path, filename),os.path.getmtime(os.path.join(local_path, filename)))
                for filename in os.listdir(local_path)
                if filename.startswith(file_name_start) and filename.endswith(file_name_end)
            ]
            localdoc = sorted(localdocfiles,key=lambda x: x[1], reverse=True)
            localfilename = os.path.join(local_path, os.path.basename(latest_remotefile))

            # 如果服务器文件时间比本地新，复制最新的文件到本机目录
            if localdoc:
                latest_localfile_mtime = localdoc[0][1]
                if latest_remotefile_mtime > latest_localfile_mtime:
                    print('现在复制', latest_remotefile, '...')
                    shutil.copy2(latest_remotefile, localfilename)
                    print(os.path.basename(latest_remotefile), '已成功复制')
                else:
                    print('文件没有更新')
            else:
                print('现在复制', latest_remotefile, '...')
                shutil.copy2(latest_remotefile, localfilename)
                print(os.path.basename(latest_remotefile), '已成功复制')

    except Exception as e:
        print("Error:", e)
        sys.exit(1)


# 定义服务器共享文件夹路径
server_path1 = "\\\\192.168.110.109\\hxq"
local_path1 = "e:\\hxq"
server_path2 = "\\\\192.168.110.109\\xxx"
local_path2 = "e:\\hxq"

connect_server(server_path1)
download_file(server_path1, local_path1, '重要气象信息',('.doc','.docx'))

connect_server(server_path2)
yuefen_dir_download(server_path2,local_path2,'中华人民',('.doc','.docx'))

